﻿using System;
using System.ServiceProcess;
using System.Windows.Forms;
using Synology.DS.Common;
using Synology.DS.Core;

namespace Synology.DS.ConfigEditor
{
	public partial class Editor : Form
	{
		public Editor()
		{
			InitializeComponent();
		}

		#region Event handlers
		private void OnLoad_Click(object sender, System.EventArgs e)
		{
			DoActionInTryCatchScope(LoadSettings);
		}

		private void OnSave_Click(object sender, System.EventArgs e)
		{
			DoActionInTryCatchScope(SaveSettings);
		}

		private void OnSaveRestart_Click(object sender, System.EventArgs e)
		{
			DoActionInTryCatchScope(SaveAndRestart);
		}

		private void OnRestart_Click(object sender, System.EventArgs e)
		{
			DoActionInTryCatchScope(Restart);
		}
		#endregion

		#region Private members
		private void DoActionInTryCatchScope(Action action)
		{
			try
			{
				action();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SaveAndRestart()
		{
			SaveSettings();

			Restart();
		}

		private void Restart()
		{
			ServiceController serviceController = new ServiceController(Const.ServiceName);
			if (serviceController.CanStop)
				serviceController.Stop();

			serviceController.Start();
			MessageBox.Show("Service was restarted successfully", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
		}

		private void SaveSettings()
		{
			var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(Const.ServiceExeFileName);
			var configurationManager = new ConfigurationManager(config, false);

			configurationManager.SynologyApiUrl = tbDiskStationUrl.Text;
			configurationManager.TorrentFilesFilter = tbFilesFilter.Text;
			configurationManager.SynologyPassword = StringEncoder.Encode(tbPassword.Text);
			configurationManager.TorrentFilesFolder = tbTorrentsFolder.Text;
			configurationManager.TorrentsArchiveFolder = tbArchiveFolder.Text;
			configurationManager.SynologyUser = tbUserName.Text;

			configurationManager.Save();
		}

		private void LoadSettings()
		{
			var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(Const.ServiceExeFileName);
			var configurationManager = new ConfigurationManager(config, false);

			tbDiskStationUrl.Text = configurationManager.SynologyApiUrl;
			tbFilesFilter.Text = configurationManager.TorrentFilesFilter;
			tbPassword.Text = StringEncoder.Decode(configurationManager.SynologyPassword);
			tbTorrentsFolder.Text = configurationManager.TorrentFilesFolder;
			tbArchiveFolder.Text = configurationManager.TorrentsArchiveFolder;
			tbUserName.Text = configurationManager.SynologyUser;
		}
		#endregion
	}
}
